<?php

require 'library/define.php';
require_once ROOT_SERVICES . DS . 'error_handler.php';
require_once ROOT_LIBRARY_RESTFUL . DS . 'restful.php';
require_once ROOT_LIBRARY_DB . DS . 'PDOWrapper.php';
require_once ROOT_LIBRARY_APC . DS . 'fileCache.php';
require_once ROOT_LIBRARY_APC . DS . 'wrapperCache.php';
require_once ROOT_LIBRARY_LAZADA . DS . 'global_vars.php';
require_once ROOT_LIBRARY_HTMLDOM . DS . 'simple_html_dom.php';
require_once ROOT_SERVICES . DS . 'service_interface.php';
require_once ROOT_SERVICES_MODEL . DS . 'models_setting.php';


class service extends restful {

    public function __construct() {
        parent::__construct();
    }

    public function router() {
        $method = isset($_REQUEST['cmd']) ? $_REQUEST['cmd'] : null;
        $classname = 'service_interface';

        if (is_callable(array($classname, $method))) {
            list($db, $cache) = $this->_init_resource();
            $respone_data = call_user_func_array(array($classname, $method), array($db, $cache, $this->_request));
            $this->response(json_encode($respone_data));
        } else {
            $this->response(json_encode(array('error' => 5, 'message' => 'service dose not exist', 'data' => '')));
        }
    }

    private function _init_resource() {
        $local_db = isset($this->_request['country']) ? $this->_request['country'] : 'vn';
        $config = include ROOT_CONFIG;
        if (isset($config['timezone'][$local_db]))
            date_default_timezone_set($config['timezone'][$local_db]);

        global_vars::instance()->set('config', $config);
        global_vars::instance()->set('local_db', $local_db);
        $db = $cache = null;

        if (array_key_exists($local_db, $config['db'])) {
            $db_config = $config['db'][$local_db];
            $db = PDOWrapper::instance();
            $db->configMaster($db_config['master']);
            $db->configSlave($db_config['slave']['host'], $db_config['slave']['name'], $db_config['slave']['user'], $db_config['slave']['password'], $db_config['slave']['port']);

            $cache = wrapperCache::GetInstance($config['apc_cache']['cache_type'], $config['apc_cache']['cache_expire'], $config['apc_cache']['cache_path']);
        } else {
            throw new PDOException('database local dose not exist');
        }

        $models_setting = new models_setting($db, $cache);
        $models_common = new models_common($db, $cache);
        
        global_vars::instance()->set('models_common', $models_common);
        global_vars::instance()->set('setting', $models_setting);

        return array($db, $cache);
    }

}

$service = new service();
$service->router();
?>


